

package net.jjjshop.front.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.jjjshop.common.entity.lbt.*;
import net.jjjshop.common.entity.user.User;
import net.jjjshop.common.entity.user.UserBill;
import net.jjjshop.common.service.lbt.LbLineClassService;
import net.jjjshop.common.service.lbt.LbLotteryOrderService;
import net.jjjshop.common.service.lbt.LbSysConfigService;
import net.jjjshop.common.service.lbt.UserBillService;
import net.jjjshop.framework.common.api.ApiResult;
import net.jjjshop.framework.log.annotation.OperationLog;
import net.jjjshop.framework.shiro.util.JwtTokenUtil;
import net.jjjshop.framework.util.LoginUtil;
import net.jjjshop.framework.util.PasswordUtil;
import net.jjjshop.front.controller.BaseController;
import net.jjjshop.front.param.user.LineUpParam;
import net.jjjshop.front.param.user.PhoneRegisterParam;
import net.jjjshop.front.param.user.UserExtractRequest;
import net.jjjshop.front.service.lbt.LbVersionService;
import net.jjjshop.front.service.user.UserService;
import net.jjjshop.front.vo.user.LoginUserTokenVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(value = "user", tags = {"用户"})
@RestController
@RequestMapping("/front/user/user")
public class UserController extends BaseController {


    @Autowired
    private UserService userService;
    @Autowired
    private UserBillService userBillService;
    @Autowired
    private LbLineClassService lineClassService;
    @Autowired
    private LbSysConfigService sysConfigService;
    @Autowired
    private LbVersionService versionService;
    @Autowired
    private LbLotteryOrderService lotteryOrderService;

    @RequestMapping(value = "/updateInfo", method = RequestMethod.POST)
    @OperationLog(name = "updateInfo")
    @ApiOperation(value = "updateInfo", response = String.class)
    public ApiResult<String> updateInfo(Integer userId, String updateType, String updateValue){
        User user = this.getUser(true);
        if(userService.updateInfo(user.getUserId(), updateType, updateValue)){
            return ApiResult.ok(null, "修改成功");
        }else{
            return ApiResult.fail("修改失败");
        }
    }

    @RequestMapping(value = "/phoneLogin", method = RequestMethod.POST)
    @OperationLog(name = "phoneLogin")
    @ApiOperation(value = "phoneLogin", response = String.class)
    public ApiResult<LoginUserTokenVo> phoneLogin(@RequestParam String mobile, @RequestParam String password){
        log.debug("phoneLogin...");
        LoginUserTokenVo user = userService.login(mobile, password);
        // 设置token响应头
        response.setHeader(JwtTokenUtil.getTokenName(""), user.getToken());
        return ApiResult.ok(user, "登录成功");
    }

    //h5注册
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @OperationLog(name = "register")
    @ApiOperation(value = "register", response = String.class)
    public ApiResult<String> register(@RequestBody PhoneRegisterParam phoneRegisterParam){
        if(userService.phoneRegister(phoneRegisterParam)){
            return ApiResult.ok(null, "注册成功");
        }else {
            return ApiResult.fail("注册失败");
        }
    }


    @ApiOperation(value = "查询公排记录")
    @RequestMapping(value = "/queryUserUpList", method = RequestMethod.POST)
    public ApiResult<?> queryUserUpList(@RequestBody LineUpParam lineUpParam){
        return ApiResult.ok(userService.queryUserUpList(lineUpParam));
    }


    @ApiOperation(value = "查询公排商家列表")
    @RequestMapping(value = "/queryShopList", method = RequestMethod.GET)
    public ApiResult<?> queryShopList(){
        return ApiResult.ok(userService.getLineClass());
    }

    @ApiOperation(value = "取消公排")
    @RequestMapping(value = "/cancelUp", method = RequestMethod.POST)
    public ApiResult<?> cancelUp(@RequestBody @Validated LbLineUpRequest request){
        Integer integer = userService.cancelUp(request);
        if (null == integer){
            return ApiResult.fail("取消失败");
        }
        if (integer.intValue() >0){
            return ApiResult.ok("取消成功，需要支付"+integer+"元邮费");
        }
        return ApiResult.fail("取消失败");
    }

    /**
     * 查询用户金币记录或佣金记录
     */
    @ApiOperation(value = "查询用户账户记录，type 0支出，1收入，category，类型")
    @PostMapping("/userBillRecord")
    public ApiResult<?>  userBillRecord(Integer type, String category, Integer page,Integer limit){
        return ApiResult.ok(userBillService.userBillRecord(LoginUtil.getLoginUserRedisVo().getUserId(),type,category,page,limit));
    }

    /**
     * 我的团队
     */
    @ApiOperation(value = "个人中心-我的团队")
    @RequestMapping(value = "/getMyTeam", method = RequestMethod.GET)
    public ApiResult<Object>  getMyTeam() {
        UserTeamResponse userTeam = userService.getUserTeam();
        return ApiResult.ok(userTeam);
    }


    /**
     * 查询直推人
     */
    @ApiOperation(value = "查询直推人")
    @RequestMapping(value = "/zPush", method = RequestMethod.GET)
    public ApiResult<?> zPush(Integer page,Integer limit) {
//        Page<User> pages = new Page<User>(page, limit);
//        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//        wrapper.select(User::getMobile,User::getNickname,User::getAvatarurl,User::getUserId,User::getLevel4);
//        wrapper.eq(User::getRefereeId,LoginUtil.getLoginUserRedisVo().getUserId());
        return ApiResult.ok(userService.getTeamData());
    }


    /**
     * 设置交易密码
     * @return 交易密码
     */
    @ApiOperation(value = "设置交易密码")
    @RequestMapping(value = "/savePayPass", method = RequestMethod.POST)
    public ApiResult<?> savePayPass(@RequestBody @Validated TradePassRequest bean) {
        if (StringUtils.isEmpty(bean.getPayPass())||bean.getPayPass().length() !=6){
            return ApiResult.fail("请输入6位新密码");
        }
        User user = this.getUser(true);

        if (userService.setPayPass(user.getMobile(),bean.getMsgCode(), bean.getPayPass(),bean.getType())){
            return ApiResult.ok(null,"设置成功");
        }
        return ApiResult.fail("设置失败");
    }

    /**
     * 设置交易密码
     * @return 交易密码
     */
    @ApiOperation(value = "重置用户登录密码")
    @RequestMapping(value = "/restLoginPass", method = RequestMethod.POST)
    public ApiResult<?> restLoginPass(@RequestBody @Validated TradePassRequest bean) {
        if (StringUtils.isEmpty(bean.getPayPass())||bean.getPayPass().length() !=6){
            return ApiResult.fail("请输入6位新密码");
        }
       String code = userService.setLoginPass(bean.getPhone(),bean.getMsgCode(), bean.getPayPass(),bean.getType());
        if ("200".equals(code)){
            return ApiResult.ok(null,"设置成功");
        }
        return ApiResult.fail(code);
    }

    /**
     * 获取公排分类
     * @return 交易密码
     */
    @ApiOperation(value = "获取公排分类")
    @RequestMapping(value = "/queryLineClass", method = RequestMethod.POST)
    public ApiResult<?> queryLineClass() {
//        List<LbLineClass> lbLineClasses = lineClassService.queryList();
        List<LbLineClass> lbLineClasses = new ArrayList<>();
        LbLineClass lbLineClass = new LbLineClass();
        lbLineClass.setTitle("公排订单");
        lbLineClass.setShopName("公排订单");
        lbLineClass.setStoreId(0);
        lbLineClasses.add(lbLineClass);
        return ApiResult.ok(lbLineClasses);
    }

    /**
     * 修改登录密码
     * @param newPass 修改登录密码
     * @return 修改登录密码
     */
    @ApiOperation(value = "修改登录密码")
    @RequestMapping(value = "/changeLoginPass", method = RequestMethod.POST)
    public ApiResult<?> 修改登录密码(@RequestParam("newPass") String newPass, @RequestParam("oldPass") String oldPass) {
        User user = this.getUser(true);

        if (StringUtils.isEmpty(newPass)||newPass.length() <6){
            return ApiResult.fail("请输入6位以上新密码");
        }

        String encryptPassword = PasswordUtil.encrypt(oldPass, user.getSalt());
        if (!encryptPassword.equals(user.getPassword())) {
            throw new AuthenticationException("旧密码不对");
        }
        user.setPassword(PasswordUtil.encrypt(newPass, user.getSalt()));
        boolean b = userService.updateById(user);
        if (b){
            return ApiResult.ok("修改成功");
        }
        return ApiResult.fail("修改失败");
    }



    /**
     * 获取系统配置
     */
    @ApiOperation(value = "获取系统配置")
    @RequestMapping(value = "/getSysConfig", method = RequestMethod.GET)
    public ApiResult<LbSysConfigEntity> getSysConfig(){
        return ApiResult.ok(sysConfigService.selectSysConfig());
    }


    @ApiOperation(value = "查询app版本更新type 1商城，2权益卡")
    @RequestMapping(value = "/getAppVersion", method = RequestMethod.GET)
    public ApiResult<?> getAppVersion(@RequestParam("type") Integer type){
        return ApiResult.ok(versionService.selectData(type));
    }


    /**
     * 查询直推人
     */
    @ApiOperation(value = "查询直推人")
    @RequestMapping(value = "/getLayerList", method = RequestMethod.GET)
    public ApiResult<?> getLayerList(Integer uid) {
        if (null == uid ){
            uid = LoginUtil.getLoginUserRedisVo().getUserId();
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(User::getMobile,User::getNickname,User::getAvatarurl,User::getUserId,User::getGradeId);
        wrapper.eq(User::getPid,uid);
//        wrapper.eq(User::getRefereeId,LoginUtil.getLoginUserRedisVo().getUserId());
        return ApiResult.ok(userService.list(wrapper));
    }

    /**
     * 查询直推人
     */
    @ApiOperation(value = "查询三条线业绩")
    @RequestMapping(value = "/getAbcMoney", method = RequestMethod.GET)
    public ApiResult<?> getAbcMoney() {
        Map<String,Object> map = new HashMap<>();
        map.put("A",0);
        map.put("B",0);
        map.put("C",0);
        User byId = userService.getById(LoginUtil.getLoginUserRedisVo().getUserId());
        if (null != byId.getAline()){
            map.put("A",userService.getAline(byId.getAline()));
        }
        if (null != byId.getBline()){
            map.put("B",userService.getAline(byId.getBline()));
        }
        if (null != byId.getCline()){
            map.put("C",userService.getAline(byId.getCline()));
        }

        return ApiResult.ok(map);
    }


    /**
     * 查询抽奖记录
     */
    @ApiOperation(value = "查询抽奖记录")
    @RequestMapping(value = "/getLotteryRecord", method = RequestMethod.GET)
    public ApiResult<?> getLotteryRecord() {
        return ApiResult.ok(lotteryOrderService.getLotteryRecord());
    }


    /**
     * 查询是否到抽奖时间
     */
    @ApiOperation(value = "查询是否到抽奖时间")
    @RequestMapping(value = "/getLotteryData", method = RequestMethod.GET)
    public ApiResult<?> getLotteryData() {
        return ApiResult.ok(lotteryOrderService.getLotteryData());
    }

    /**
     * 查询抽奖结果
     */
    @ApiOperation(value = "查询抽奖结果")
    @RequestMapping(value = "/getQueryLottery", method = RequestMethod.GET)
    public ApiResult<?> getQueryLottery() {
        return ApiResult.ok(lotteryOrderService.getQueryLottery());
    }

    /**
     * 查询抽奖结果
     */
    @ApiOperation(value = "查询抽奖结果")
    @RequestMapping(value = "/queryResult", method = RequestMethod.GET)
    public ApiResult<?> queryResult() {
        return ApiResult.ok(lotteryOrderService.queryResult());
    }

    /**
     * 查询月度分红池数据
     */
    @ApiOperation(value = "查询月度分红池数据")
    @RequestMapping(value = "/selectPoolData", method = RequestMethod.POST)
    public ApiResult<?> selectPoolData(){

        LbSysConfigEntity lbSysConfigEntity = sysConfigService.selectSysConfig();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getLevel4,4);
        wrapper.eq(User::getLevelControl,1);
        List<User> users = userService.list(wrapper);
        Map<String,Object> map = new HashMap<>();
        map.put("pool1",lbSysConfigEntity.getPool1());
        map.put("pool2",lbSysConfigEntity.getPool2());
        if (null != users && !users.isEmpty()){
            map.put("zdNum",users.size());
        }else{
            map.put("zdNum",0);
        }

        LambdaQueryWrapper<User> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(User::getLevel4,5);
        wrapper2.eq(User::getLevelControl,1);
        List<User> users2 = userService.list(wrapper2);
        if (null != users2 && !users2.isEmpty()){
            map.put("lcNum",users2.size());
        }else{
            map.put("lcNum",0);
        }

        return ApiResult.ok(map);
    }
}
